<?php
    defined('M2_MICRO') or die('Direct Access to this location is not allowed.');

    /**
      * @desc View class
      * @name $view
      * @package M2 Micro Framework
      * @subpackage Modules
      * @author Alexander Chaika
      */
    class View extends Message {
        
        /**
          * View class constructor
          */
        public function __construct() {}
        
        /**
          * Render action
          * @param array $options
          */
        public function render($options = null) {
            // check empty options
            if (empty($options)) {
                $options = array();
            }
            
            // check empty format
            if (!isset($options['format'])) {
                $options['format'] = 'log';
            }            
            
            // route output
            switch ($options['format']) {
                case 'html':
                    // set headers
                    header('HTTP/1.1 200 OK');
                    header('Content-Type: text/html; charset=UTF-8');
                    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
                    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
                    header('Cache-Control: no-cache, must-revalidate');
                    header('Pragma: no-cache');
                    
                    // output html data
                    echo $options['data'];
                    break;
                case 'page':
                    // set headers
                    header('HTTP/1.1 200 OK');
                    header('Content-Type: text/html; charset=UTF-8');
                    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
                    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
                    header('Cache-Control: no-cache, must-revalidate');
                    header('Pragma: no-cache');
                    
                    // output html data
                    echo $this->wrapPage($options);
                    break;
                case 'log':
                default:
                    // Add log record
                    $message = 'Import {'.$options['feed'].'} successfull '
                             . '(i:'.(int)$options['result']['inserted']
                             . ';u:'.(int)$options['result']['updated']
                             . ';d:'.(int)$options['result']['deleted']
                             . ';s:'.(int)$options['result']['skipped']
                             . ';a:'.(int)$options['result']['all'].')';

                    $this->cleanMessage($message, true);
                break;
            }
            return;
        }
        
        /**
          * Wrap HTML data to Page
          * @param array $options
          * @return string $html
          */
        public function wrapPage($options) {
            // get form contents
            $options['template'] = 'default';
            $options['type'] = '';
            $options['name'] = 'index';
            return $this->getContents($options, false);
        }
        
        /**
          * Get HTML contents for TYPE/NAME entity
          * @param array $options
          * @param bool $mode OPTIONAL if true - template view
          * @return string $html
          */
        public function getContents($options, $view = true) {
            // get config
            $config = System::getInstance()->getConfig();
            
            // get content type
            if (isset($options['type'])) {
                $type = $options['type'] . DS;
            } else {
                $type = '';
            }
            
            // get content type
            if (isset($options['name'])) {
                $name = $options['name'];
            } else {
                $name = 'index';
            }
            
            // compile template prefix and postfix
            $prefix = $config['doc_root'] . DS . 'templates' . DS;
            if ($view) {
                $postfix = DS . 'view' . DS . $type . $name . '.php';
            } else {
                $postfix = DS . $type . $name . '.php';
            }
            
            // check content file existance
            $content_file_name = convertOSPath($prefix . $options['template'] . $postfix);
            if (!file_exists($content_file_name)) {
                // check default template for view
                $content_file_name = convertOSPath($prefix . $config['template'] . $postfix);
                if (!file_exists($content_file_name)) {
                    $content_file = array(
                        (!empty($options['template']) ? $options['template'] : $config['template']),
                        (!empty($type) ? $options['type'] : 'none'),
                        (!empty($options['name']) ? $options['name'] : 'Undefined')
                    );
                    return $this->throwMessage('Template file for ' . implode('/', $content_file) . ' not found');
                }
            }
            
            // render to buffer
            ob_start();

            // get contents
            include $content_file_name;
            $result = ob_get_contents();

            // clean buffer
            ob_end_clean();

            return $result;
        }
        
        /**
          * Offline render action
          * @param array $options OPTIONAL
          */
        public function offline($options = null) {
            $message = $this->getLastFromStack();
            echo '<code>['.getErrorStringFromInt($message['level']).']'.$message['message'].'</code>';
            echo '<code>['.var_dump(debug_backtrace()).'</code>';
            return;
        }
    }
?>
